package com.ewei.web.common.shiro.xmemcached;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import net.rubyeye.xmemcached.CASOperation;
import net.rubyeye.xmemcached.XMemcachedClient;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
public class XmemcachedCache implements Cache<String,Object>{
	
	private XMemcachedClient client; 
	
	public XmemcachedCache(XMemcachedClient client){
		this.client = client;
	}

	@Override
	public Object get(String key) throws CacheException {
		try {
			return client.get(key);
		} catch (Exception e) {
			throw new CacheException(e);
		}
	}

	@Override
	public Object put(String key, Object value) throws CacheException {
		final Object newValue = value;
		try {
			return client.cas(key, 60*60*24,new CASOperation<Object>() {
				@Override
				public int getMaxTries() {
					return 5;
				}

				@Override
				public Object getNewValue(long currentCAS, Object currentValue) {
					return newValue;
				}
			
			});//默认缓存24h
		} catch (Exception e) {
			throw new CacheException(e);
		}
	}

	@Override
	public Object remove(String key) throws CacheException {
		try {
			return client.delete(key,10);//10秒内不删除，不要怪我不义
		} catch (Exception e) {
			throw new CacheException(e);
		}
	}

	@Override
	public void clear() throws CacheException {
		try{
			client.flushAll();//写到这我已经崩溃了
		}catch(Exception e){
			throw new CacheException(e);
		}
	}

	@SuppressWarnings("unused")
	@Override
	public int size() {//大数据求大小，泥坑(这里先不写,待我研究研究）
//		try{
//			Iterator<Map<String,String>> iterator = client.getStatsByItem("items").values().iterator();
//		}catch(Exception e){
//			throw new CacheException(e);
//		}
		return 0;
	}

	@Override
	public Set<String> keys() {//大数据遍历，泥坑（介个api都删了..)
		return new HashSet<String>();
	}

	@Override
	public Collection<Object> values() {
		return new HashSet<Object>();
	}
	

}
